import Vue from "vue";
import jsComponents from "./components/jsComponents";

const initComponent = (ops, instance) => {
  return new Promise((resolve, reject) => {
    try {
      const componentOps = ops.default();
      let p = [];
      if (componentOps.component) {
        for (let n in componentOps.component) {
          p.push(initComponent(componentOps.component[n], instance));
        }
      }
      Promise.all(p)
        .then((res) => {
          const component = createComponent(ops, componentOps);
          if (ops.router) {
            createRouter(instance, {
              ...ops.router,
              component: component,
            });
          }
          resolve();
        })
        .catch((e) => reject(e));
    } catch (e) {
      reject(e);
    }
  });
};

const createRouter = (instance, ops) => {
  instance.$router.addRoute(ops.name, ops);
};

const createComponent = (ops, json) => {
  return Vue.component(ops.moduleName, {
    template: ops.moduleTemplate,
    ...json,
  });
};

// instance = new Vue()
export const jsonLoader = (instance) => {
  if (jsComponents.module) {
    let p = [];
    jsComponents.module.map((item) => {
      p.push(initComponent(item, instance));
    });
    Promise.all(p).catch((e) => console.error(e));
  } else if (jsComponents) {
    initComponent(jsComponents, instance).catch((e) => console.error(e));
  }
};
